# -*- coding:utf-8 -*-

import datetime
import matplotlib.pyplot as plt

class Weather(object):

    def __init__(self,rd,h,pr,sp,wd,ws,t,rh,pe):
        self.rec_date = rd
        self.hour = h
        self.pressure = pr
        self.sea_pressure = sp
        self.wind_direction = wd
        self.wind_speed = ws
        self.temperature = t
        self.rel_humidity = rh
        self.precipitation = pe

    def print_info(self):
        print 'date=',self.rec_date,('hour=%d pressure=%f sea_pressure=%f wind_drection=%f wind_speed=%f temperature=%f rel_humidity=%f precipitation=%f'
        %(self.hour,self.pressure,self.sea_pressure,self.wind_direction,self.wind_speed,self.temperature,self.rel_humidity,self.precipitation))

class Weathers(object):

    def __init__(self):
        self.weathers=[]

    def add_weather(self, w):
        if isinstance(w,Weather):
            self.weathers.append(w)
        else:
            print 'not Weather class'

    def print_info(self):
        for i in self.weathers:
            i.print_info()

    def available_dates(self):
        res=[]
        for i in self.weathers:
            if not i.rec_date in res:
                res.append(i.rec_date)
        return res
        
    def get(self, dates, name, seg1, seg2):
        '''
            区间内每小时平均值
        '''
        res = {}
        for i in dates:
            res[i] = []
        for obj in self.weathers:
            if obj.rec_date in dates and obj.hour * 3 >= seg1 and obj.hour * 3 + 1e-5 < seg2:
                res[obj.rec_date].append(eval('obj.'+name))
        return [(sum(res[k])/len(res[k])) for k in sorted(res.keys())]
    def visualize(self, name, name2 = None):
        '''
            name and name2 is y axis variables
            rec_date is x axis variable
        '''
        y = [eval('obj.'+name) for obj in self.weathers]
        meany = sum(y) * 1.0 / len(y)
        x = [eval('obj.rec_date') for obj in self.weathers]
        plt.figure(figsize=(20,10))
        plt.plot(x,y,label=name,color="red",linewidth=1)
        if(name2 is not None):
            z = [eval('obj.'+name2) for obj in self.weathers]
            meanz = sum(z) * 1.0 / len(z)
            z = [v - meanz + meany for v in z]
            plt.plot(x,z,label=name2,color="blue",linewidth=1)
        plt.legend()
        plt.show()

def Weathers_test():
    a=Weather(datetime.date(2017,3,17),1,2.2,3.3,4.4,5.5,6.6,7.7,8.8)
    b=Weathers()
    b.add_weather(a)
    b.print_info()
